package com.zhongbo.java.websocket.service;

import cn.hutool.json.JSON;
import com.zhongbo.java.websocket.config.RedisConfig;
import com.zhongbo.java.websocket.web.websocket.Chat1WebSocket;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.websocket.Session;
import java.io.IOException;

/**
 * 说明：
 * redis 消息发布和订阅消息
 *
 * @author 钟波dellNotebook
 * @since 2025年03月24日 星期一 15:19:36
 */
@Component
@Slf4j
public class RedisMessagePublisher {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    // 发布消息
    public void publishMessage(String message){
        // 向指定channel发送消息
        redisTemplate.convertAndSend(RedisConfig.CHAT_CHANNEL, message);
    }

    // 接收消息

    // 消息监听容器（需配置）
    // 接收消息,并且广播给本地所有session
    @Bean
    public MessageListenerAdapter listenerAdapter() {
        return new MessageListenerAdapter((MessageListener) (message, pattern) -> {
            String msg = new String(message.getBody());
            log.info("收到消息 : {}",msg);
            for (Session session : Chat1WebSocket.sessionMap.values()) {
                // 给所有的客户端推送ws消息
                try {
                    session.getBasicRemote().sendText(msg);
                } catch (IOException e) {
                    log.error("发送消息异常", e);
                }
            }
        });
    }

}
